import { useState, useCallback, useEffect, useMemo } from 'react';
import { Button, Space } from 'antd';
import DataEdit from '@/components/base/DataEdit';
import Sheets from '@/components/DataSheet';
import PageHeader from '@/components/page/PageHeader';
import { history } from 'umi';
import { getReptData, exportRept } from '@/services/excelReport';
import { Base64 } from 'js-base64';
import { format } from '@/utils/datetime';

import _ from 'lodash';
export default () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [params, setParams] = useState<Record<string, string>>({});
  const [tplData, setTplData] = useState<API.Template | undefined>(undefined);
  const loadData = useCallback(() => {
    const path = history.location.pathname;
    const index = path.lastIndexOf('/');
    const reptName = path.substring(index + 1, path.length);
    setLoading(loading);
    const reqParams = params;
    tplData?.params?.forEach((p) => {
      if (p.dataType === 'number') {
        reqParams[p.name] = '' + reqParams[p.name];
      } else if (p.dataType === 'date') {
        reqParams[p.name] = format(reqParams[p.name], 'yyyy-MM-dd');
      }
    });
    getReptData(reptName, reqParams)
      .then(function (data) {
        setTplData(data);
      })
      .catch(function (ex) {
        console.error('请求报表', reptName, '错误', ex);
      })
      .finally(function () {
        setLoading(false);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loading, params]);
  const exportXlsx = useCallback(() => {
    const path = history.location.pathname;
    const index = path.lastIndexOf('/');
    const reptName = path.substring(index + 1, path.length);
    setLoading(loading);
    exportRept(reptName, params)
      .then(function (resp) {
        const a = document.createElement('a');
        const url = window.URL.createObjectURL(resp.data);
        const filename = resp.response.headers.get('Content-Disposition');
        a.href = url;
        a.download = Base64.decode(filename!);
        document.body.appendChild(a);
        a.click();
        setTimeout(function () {
          document.body.removeChild(a);
        }, 1000);
        window.URL.revokeObjectURL(url);
      })
      .catch(function (ex) {
        console.error('请求报表', reptName, '错误', ex);
      })
      .finally(function () {
        setLoading(false);
      });
  }, [loading, params]);
  useEffect(() => {
    loadData();
  }, [loadData]);
  const toolBar = useMemo(() => {
    if (_.isEmpty(tplData)) {
      return null;
    }
    const pConts: API.Control[] = [];
    const pVals = !params ? {} : params;
    tplData!.params.forEach((p) => {
      if (params && params[p.name]) {
        pVals[p.name] = params[p.name];
      } else {
        pVals[p.name] = p.initVal;
      }
      if (p.type === 'none') {
        return;
      }
      const pCont: API.Control = {
        name: p.name,
        label: p.label,
        type: p.type as 'text' | 'number' | 'select' | 'date' | 'datetime' | 'month' | 'search',
        dataType:
          p.dataType === 'int' || p.dataType === 'float'
            ? 'number'
            : (p.dataType as 'date' | 'datetime' | 'string'),
        multiple: p.multiSelect,
        placeholder: p.placeholder,
        options: p.data,
        fetch: p.fetch,
        grid: p.grid,
        hasAll: p.hasAll,
        precision: 2,
      };
      pConts.push(pCont);
    });
    return (
      <DataEdit
        controls={pConts}
        initVals={params}
        showType="inner"
        layout="inline"
        grid={false}
        autoFocusFirstInput={false}
        onSumit={async (vals) => {
          setParams(vals as Record<string, string>);
        }}
        renderButtons={(p) => {
          return [
            <Space key="extraButtons" style={{ marginBottom: 15 }}>
              <Button type="primary" key="createRep" onClick={() => p.form?.submit?.()}>
                查询
              </Button>
              <Button type="primary" key="exportRep" onClick={() => exportXlsx()}>
                导出
              </Button>
              <span style={{ marginLeft: 50 }}>{tplData?.remarks}</span>
            </Space>,
          ];
        }}
      />
    );
  }, [exportXlsx, params, tplData]);
  if (_.isEmpty(tplData)) {
    return <></>;
  }
  if (loading) {
    return <></>;
  }
  return (
    <PageHeader>
      {toolBar}
      <Sheets
        sheets={tplData!.sheets}
        /** 颜色列表 */
        colors={tplData!.colors}
        /** 宽度调整系数 */
        widthrRatio={tplData!.widthrRatio}
        /** 高度调整系数 */
        heightRatio={tplData!.heightRatio}
        /** 表格行头调整系数，用与行头对齐 */
        rowHeadTopOff={tplData!.rowHeadTopOff}
      />
    </PageHeader>
  );
};
